package controller

import (
	"net/http"
	"sync"

	"commonUtils/utils"
	"commonUtils/web/plugin"
)

type Namespace struct {
	Name         string
	controllers  map[string]Controller
	muController sync.RWMutex
	checkAuth    func(*Context) (string, int)
	baseCheck    func(*Context) (string, int)
}

func NewNamespace(name string) *Namespace {
	namespace := &Namespace{
		Name:        name,
		controllers: make(map[string]Controller),
	}
	return namespace
}

func (m *Namespace) CheckAuthCall(f func(*Context) (string, int)) {
	m.checkAuth = f
}

func (m *Namespace) BaseCheckCall(f func(*Context) (string, int)) {
	m.baseCheck = f
}

func (n *Namespace) Regist(ctrl ...Controller) {
	n.muController.Lock()
	defer n.muController.Unlock()
	for _, c := range ctrl {
		if _, ok := n.controllers[c.GetName()]; ok {
			utils.Warning("namespace %s already had cotroller %s, overwrite.", n.Name, c.GetName())
		}
		n.controllers[c.GetName()] = c
		c.SetSpacename(n.Name)
		c.initTemps()
	}
}

func (n *Namespace) RouteName(name string) string {
	if !utils.BeginWith(name, "/") {
		name = "/" + name
	}
	// return strings.ToLower("/" + n.Name + name)
	return "/" + n.Name + name
}
func (n *Namespace) AllRoutes() map[string]http.Handler {
	n.muController.RLock()
	defer n.muController.RUnlock()
	if len(n.controllers) == 0 {
		return nil
	}

	isIndexCtrl := false
	ret := make(map[string]http.Handler)
	for _, c := range n.controllers {
		handles := c.Handlers(c)
		if len(handles) > 0 {
			isIndexCtrl = "index" == c.GetName()
			for name, handle := range handles {
				if n.Name != "" {
					routeName := n.RouteName(name)
					ret[routeName] = plugin.Manager().InstallHandler(handle)
					if name == "/index/" {
						routName1 := n.RouteName("")
						ret[routName1] = ret[routeName]
						routName1 = routName1[0 : len(routName1)-1]
						ret[routName1] = ret[routeName]
					}
				} else {
					ret[name] = plugin.Manager().InstallHandler(handle)
					if name == "/index/" && isIndexCtrl {
						ret["/"] = ret[name]
					}
				}
			}
		}
	}
	return ret
}
